package unit15.randomAccess;

import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.io.Serializable;
import java.text.ParseException;
import java.util.Calendar;
import java.util.GregorianCalendar;

public class RandomAccessTest implements Serializable{
	/**
	 * 
	 */
	private static final long serialVersionUID = -2993189891929050072L;
	public static void main(String[] args) throws Exception {
		Employee[] staff=new Employee[3];
		staff[0]=new Employee("Alice", 50000, 1997,6,6);
		staff[1]=new Employee("Mike", 60000, 1998,4,4);
		staff[2]=new Employee("Ben", 70000, 1999,7,7);
		
		try(DataOutputStream out=new DataOutputStream(new FileOutputStream("C:\\Users\\asus\\Desktop\\Employee.dat"))) {
//			save all employee records to the file employee.txt
			for(Employee e:staff){
				writeData(out,e);
			}
			try(RandomAccessFile in=new RandomAccessFile("C:\\Users\\asus\\Desktop\\Employee.dat","r")){
//				retrieve all records into a new array
				int n=(int) (in.length()/Employee.RECODE_SIZE);
				Employee[] newStaff=new Employee[n];
				
				for(int x=n-1;x>=0;x--){
					newStaff[x]=new Employee();
					in.seek(x*Employee.RECODE_SIZE);
					newStaff[x]=readData(in);
				}
				for(Employee e:newStaff){
					System.out.println(e);
				}
			}
		}
	}
	/**
	 * 
	 * @param in
	 * @return
	 * @throws IOException 
	 * @throws ParseException 
	 */
	private static Employee readData(RandomAccessFile in) throws IOException, ParseException {
		// TODO Auto-generated method stub
		String name=DataIO.readFixedString(Employee.RECODE_SIZE, in);
		int salary=in.readInt();
		int year=in.readInt();
		int month=in.readInt();
		int day=in.readInt();
		return new Employee(name, salary, year, month, day);
	}
	/**
	 * 
	 * @param out
	 * @param e
	 * @throws IOException 
	 */
	private static void writeData(DataOutputStream out, Employee e) throws IOException {
		DataIO.writeFixedString(e.getUsername(), Employee.RECODE_SIZE, out);
		out.writeInt(e.getSalary());
		GregorianCalendar calendar=new GregorianCalendar();
		calendar.setTime(e.getDate());
		out.writeInt(Calendar.YEAR);
		out.writeInt(Calendar.MONTH);
		out.writeInt(Calendar.DAY_OF_MONTH);
		}
}
